import tkinter as tk
from tkinter import messagebox as msgbox
from tkinter import ttk
from tkinter import filedialog
from tkinter.font import Font
from tktooltip import ToolTip
from download import Downloader
import threading
import os


class MainFrm:
    """
    主界面
    """

    def __create_tip(self, widget:tk.Widget, text:str):
        ToolTip(widget,text)

    def __center_window(self, w: int, h: int):
        """
        窗口显示在屏幕居中位置
        """
        screen_w = self.root.winfo_screenwidth()
        screen_h = self.root.winfo_screenheight()
        x = int(screen_w / 2 - w / 2)
        y = int(screen_h / 2 - h / 2)
        self.root.geometry(f'{w}x{h}+{x}+{y}')

    def __init__(self):
        """
        主界面初始化
        """
        self.root = tk.Tk()
        self.default_font = Font(root=self.root,family='微软雅黑',size=8)
        self.bold_font = Font(root=self.root,family='微软雅黑',size=8,weight='bold')
        
        # 设置窗口显示位置
        self.__center_window(400, 300)
        self.root.title('多线程下载器')
        self.root.iconbitmap('imgs/download.ico')
        # 禁止窗口大小调整（禁用最大化按钮）
        self.root.resizable(False, False)

        ### main_frame
        main_frame = tk.Frame(self.root, background='#CCCCCC',bd=1)
        main_frame.pack(fill='both',expand=True)
        
        ### url_label
        tk.Label(main_frame,bg='#CCCCCC', text='下载地址:', font=self.default_font, justify='left').place(x=10,y=10,width=50)

        ### url_tbx
        self.url_tbx = tk.Entry(main_frame, font=self.default_font)
        self.url_tbx.place(x=60,y=10,width=330)
        
        ### thread_count_label
        tk.Label(main_frame,bg='#CCCCCC', text='线 程 数:', font=self.default_font, justify='left').place(x=10,y=40,width=50)
        
        ### thread_count_tbx
        self.thread_count_tbx = tk.Entry(main_frame, font=self.default_font)
        self.thread_count_tbx.insert(0,str(os.cpu_count())) # 设置默认线程数
        self.thread_count_tbx.place(x=60,y=40,width=30)

        ### thread_count_des_label
        tk.Label(main_frame,bg='#CCCCCC', text='(默认:逻辑处理器数量)', font=self.default_font, justify='left').place(x=90,y=40,width=120)

        ### proxy_label_frame
        proxy_label_frame = tk.LabelFrame(main_frame, bg='#CCCCCC',text='代理配置',width=380,height=100,font=self.default_font)
        proxy_label_frame.place(x=10, y=70)

        ### proxy_url_label
        tk.Label(proxy_label_frame,bg='#CCCCCC', text='代理地址:', font=self.default_font, justify='left').place(x=10,y=10,width=50)

        ### proxy_url_tbx
        self.proxy_url_tbx = tk.Entry(proxy_label_frame, font=self.default_font)
        self.proxy_url_tbx.place(x=60,y=10,width=310)

        ### proxy_username_label
        tk.Label(proxy_label_frame,bg='#CCCCCC', text='代理用户:', font=self.default_font, justify='left').place(x=10,y=40,width=50)

        ### proxy_username_tbx
        self.proxy_username_tbx = tk.Entry(proxy_label_frame, font=self.default_font)
        self.proxy_username_tbx.place(x=60,y=40,width=120)

        ### proxy_password_label
        tk.Label(proxy_label_frame,bg='#CCCCCC', text='代理密码:', font=self.default_font, justify='left').place(x=200,y=40,width=50)

        ### proxy_password_tbx
        self.proxy_password_tbx = tk.Entry(proxy_label_frame, font=self.default_font)
        self.proxy_password_tbx.place(x=250,y=40,width=120)

        ### download_progressbar
        self.download_progressbar = ttk.Progressbar(main_frame,maximum=100,value=0)
        self.download_progressbar.place(x=10,y=180,width=340,height=20)

        ### download_progressbar_label
        self.download_progressbar_label = tk.Label(main_frame,bg='#CCCCCC', font=self.default_font)
        self.download_progressbar_label.config(text='0%')
        self.download_progressbar_label.place(x=350,y=180,height=20,width=40)

        ### proxy_enabled_label
        tk.Label(main_frame,bg='#CCCCCC', text='启用代理:', font=self.default_font, justify='left').place(x=10,y=210,width=50)

        ### proxy_enabled_checkedbox
        self.proxy_enabled = tk.BooleanVar(self.root,value=False)
        self.proxy_enabled_checkedbox = tk.Checkbutton(main_frame,bg='#CCCCCC',variable=self.proxy_enabled, onvalue=True, offvalue=False)
        self.proxy_enabled_checkedbox.place(x=60,y=210,width=20,height=20)

        ### download_btn
        download_btn = tk.Button(main_frame,text='下载', command=self.__download_btn_click)
        download_btn.place(x=310,y=210,width=80,height=20)

        ### desc_tbx_frame
        desc_tbx_frame = ttk.Frame(main_frame)
        desc_tbx_frame.place(x=10,y=240,width=380,height=50)

        ### desc_tbx
        self.desc_tbx = tk.Text(desc_tbx_frame,state='disabled')
        self.desc_tbx.pack(fill='both',expand=True)

        
    def __file_extens(self, url:str):
        """
        从url解析文件后缀
        """
        url_path = url.split('?')[0]
        sub_start = url_path.rfind('.')
        suffix = ''
        if sub_start != -1:
            suffix = url_path[sub_start:]
        file_name = url_path[url_path.rfind('/')+1:]
        return [file_name, suffix]
            

    def __update_progress(self, value):
        """
        更新进度条
        """
        self.download_progressbar.config(value=value)
        self.download_progressbar_label.config(text=f'{value}%')
        print('xxx',value)
        self.root.update()
    
    def __download_btn_click(self):
        """
        下载按钮单击事件
        """
        url = self.url_tbx.get()
        if url is None or url == '':
            msgbox.showerror('系统提示', '下载地址不能为空！')
            self.url_tbx.focus()
            return
        if not (url.startswith('http://') or url.startswith('https://')):
            msgbox.showerror('系统提示', '下载地址协议不支持！')
            self.url_tbx.focus()
            return

        thread_count = self.thread_count_tbx.get()
        proxy = {}
        if  self.proxy_enabled.get():
            if not self.proxy_url_tbx.get() :
                msgbox.showerror('系统提示', '请输入代理地址')
                return
            proxy['url'] = self.proxy_url_tbx.get()
            proxy['username'] = self.proxy_username_tbx.get()
            proxy['password'] = self.proxy_password_tbx.get()
        file_info = self.__file_extens(url)
        save_file = filedialog.asksaveasfilename(initialfile=file_info[0],filetypes=[('{}文件'.format(file_info[1][1:]),file_info[1])],title='保存文件')
        if save_file:
            downloader = Downloader(url,int(thread_count))
            downloader.set_proxy(proxy)
            downloader.set_savefile(save_file)
            downloader.set_update_progress_handler(self.__update_progress)
            try:
                threading.Thread(target=downloader.download).start()
            except Exception as e:
                msgbox.showerror('系统提示', '下载失败')
        
        
        
    def show(self):
        """
        显示主窗体
        """
        self.root.mainloop()
